# _*_ coding: utf-8 _*_
__author__ = 'Haoge'
from django.views.generic import TemplateView, ListView, View
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView, View
from django.shortcuts import render,render_to_response,HttpResponse
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from resources.models import ServerGroup,NewServer

# 资产组
class GroupListView(LoginRequiredMixin, TemplateView):
	template_name = 'groups/group_list.html'

	def get(self, request):
		user = request.user.username
		obj_groups = ServerGroup.objects.all()
		obj_newserver = NewServer.objects.all()


		#反查方法
		#a_id = LinkPerson.objects.get(id=6).group.name
		#lgroup = LinkGroup.objects.get(id=18)
		#mm = lgroup.linkgroup.all()
		return render_to_response('groups/group_list.html', locals())

class GroupCreateView(LoginRequiredMixin, TemplateView):
	template_name = 'groups/group_create.html'

	def get(self, request):
		user = request.user.username
		obj_groups = ServerGroup.objects.all()
		obj_newserver = NewServer.objects.all()
		return render_to_response('groups/group_create.html', locals())

	def post(self,request):

		name = request.POST.get('name')
		info = request.POST.get('info')
		memberslist = request.POST.getlist('members')
		ServerGroup.objects.create(name=name,info=info)

		gp = ServerGroup.objects.get(name=name)
		for server_id in memberslist:
			lp = NewServer.objects.get(id=server_id)
			lp.server_group = gp
			lp.save()
		return HttpResponseRedirect('/resources/group/list/')



class GroupEditView(LoginRequiredMixin, TemplateView):
	template_name = 'groups/group_edit.html'

	def get(self, request):
		id = request.GET.get('id')
		obj_group = ServerGroup.objects.get(id=id)
		obj_newserver = NewServer.objects.all()
		return render_to_response('groups/group_edit.html', locals())

	def post(self,request):
		id = request.POST.get('id')
		name = request.POST.get('name')
		info = request.POST.get('info','')
		memberslist = request.POST.getlist('members')
		print ('id is ',id)
		print('name is ', name)
		print('memberslist is ', memberslist)
		ServerGroup.objects.filter(id=id).update(name=name,info=info)
		lgp = ServerGroup.objects.get(id=id)
		# lgp.gl.clear()

		# 多对多添加
		lp = NewServer.objects.filter(id__in=memberslist)
		lgp.servergroup.set(lp)
		lgp.save()
		return HttpResponseRedirect('/resources/group/list/')


class GroupDeleteView(LoginRequiredMixin, TemplateView):

	def post(self,request):
		ret = {'status': 0}
		servergroup_id = request.POST.get('servergroup_id')
		lp = ServerGroup.objects.get(id=servergroup_id)
		lp.delete()
		ret['msg'] = '资产组删除成功'
		return JsonResponse(ret)